package com.yonyou.crm.sys.dynamic.filter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.yonyou.crm.sys.dynamic.builder.DynamicContentBuilder;
import com.yonyou.crm.sys.dynamic.builder.Field;
import com.yonyou.crm.sys.dynamic.builder.Link;
import com.yonyou.crm.sys.dynamic.entity.DynamicVO;

public class BusiFilter {
	
	private Field fromField;
	private Field toField;
	
	
	public BusiFilter(Field fromField, Field toField) {
		super();
		this.fromField = fromField;
		this.toField = toField;
	}

	public Field getFromField() {
		return fromField;
	}

	public void setFromField(Field fromField) {
		this.fromField = fromField;
	}

	public Field getToField() {
		return toField;
	}

	public void setToField(Field toField) {
		this.toField = toField;
	}

	public void doFilter(DynamicVO dym) {
		String content = dym.getContent();
		
		Map<String,Class<?>> fieldClassMap = new HashMap<String,Class<?>>();
		fieldClassMap.put("link", Link.class);
		JSONArray arr =  JSONArray.fromObject(content);
		List<Field> result = new ArrayList<Field>();
		for(int i=0,len=arr.size();i<len;i++) {
			JSONObject obj = (JSONObject)arr.get(i);
			Field f = (Field) JSONObject.toBean(obj, Field.class, fieldClassMap);
			if(f.equals(fromField)) {
				f = toField;
			}
			result.add(f);
		}
		DynamicContentBuilder builder = new DynamicContentBuilder(result);
		dym.setContent(builder.toJSON());
	}
}
